package springboot.common_utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author daiqiang

 */
//druid 连接池的工具类
public class JDBCUtils {
//    1.定义成员变量Datasource
 private static  DataSource ds;
 static {
           //1.加载配置文件
     Properties pro=new Properties();
    // pro.load(new FileReader  自定义druid.properties
     try {
         pro.load(new FileReader("D:\\日常工作\\A_开发笔记\\A_notes\\1.java\\java\\springboot06_ssmp_模版案列\\src\\main\\druid.properties"));
     } catch (IOException e) {
         e.printStackTrace();
     }
     try {
         pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
         //2.获取Datasource
         ds= DruidDataSourceFactory.createDataSource(pro);
     } catch (IOException e) {
         e.printStackTrace();
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

     // 获取链接
    public static  Connection getConnection() throws SQLException {
     return ds.getConnection();
    }
    // 释放资源
    public static void  close(Statement stmt ,Connection conn){
     /*if (stmt!=null){
         try {
             stmt.close();
         } catch (SQLException throwables) {
             throwables.printStackTrace();
         }
     }
        if (conn!=null){
            try {
                stmt.close();//归还链接
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }*/
        close(null,stmt, conn);
    }
    // 释放资源
    public static void  close(ResultSet rs,Statement stmt , Connection conn){
        if (rs!=null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (rs!=null){
            try {
                stmt.close();//归还链接
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    // 获取连接池方法
    public static DataSource getDataSource(){
        return ds;
    }

}
